package com.spring.demo.authenticator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.spring.demo.domain.User;
import com.spring.demo.service.UserService;

public class Authenticator implements UserDetailsService {
	
	@Autowired
	private UserService userService;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		User user = userService.findByLoginName(username);
		if (user != null) {
			if (user.getLoginName().equals(username)) {
				return new org.springframework.security.core.userdetails.User(user.getLoginName(), user.getPassword(), 
						true, true, true, true, getAuthorities(username));
			}
		}
		throw new UsernameNotFoundException("User " + username + " has no GrantedAuthority");
	}

	private Collection<? extends GrantedAuthority> getAuthorities(String username) {
		List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
		grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return grantedAuthorities;
	}

}
